"""
Created by PyCharm.
User: Lzn
Date: 2021/9/11
Time: 23:54
"""

import requests
import urllib3

urllib3.disable_warnings()
import re
import json
import base64


def get_douyin(url):
    # 模拟手机访问
    kv = {
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3'}

    # 获取视频id
    item_id = requests.get(url, headers=kv).url.split('/')[5]

    # 获取json
    html_url = 'https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=' + item_id
    r = requests.get(html_url, headers=kv).json()

    real_url = r['item_list'][0]['video']['play_addr']['url_list'][0].replace('/playwm/', '/play/')
    return real_url


def get_xigua(url):
    cookie = '__ac_nonce=06140d19f0034d5871515; __ac_signature=_02B4Z6wo00f01NtoMOgAAIDBUCOrC4RFQejbSDRAAFeg54; ttcid=b4c488e3bc7b400dafb737c9bba0819a27; MONITOR_WEB_ID=2c165e2a-4fec-40ec-87e5-7440f0ec4fda; ttwid=1%7CIL-2LKVdcs63_Ymk_mYmD4yl1_yJxaUNxSgvhVMPfkE%7C1631637920%7Cb5b7e7f17bc8822b2b30e05edc36a119fc0332fe053bc8c0c06f2648b6df1507; ixigua-a-s=0'
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
        "cookie": cookie
    }

    response = requests.get(url, verify=False, headers=headers).text
    pattern = re.compile('(?<=window._SSR_HYDRATED_DATA=).*?(?=</script>)')
    jsonResult = pattern.findall(response)[0]
    jsonResult = jsonResult.replace(':undefined', ':"undefined"')
    jsonData = json.loads(jsonResult)
    infor = jsonData['anyVideo']['gidInformation']['packerData']['video']
    normal = infor['videoResource']['normal']
    if 'video_list' in normal.keys():
        videoUrl = normal['video_list']['video_1']['main_url']
    else:
        print('未获取到源地址')
    real_url = base64.b64decode(videoUrl).decode("utf-8")

    return real_url


if __name__ == '__main__':
    url = input("请输入视频地址: ")

    # 判断解析类型
    type = re.search(r'([a-z]+)://([a-z]+).([a-z]+)', url, re.M | re.I).group(3)

    if type == 'douyin':
        real_url = get_douyin(url)
    elif type == 'ixigua':
        real_url = get_xigua(url)
    else:
        real_url = "抱歉, 此网站暂不支持解析"

    # 输出真实链接
    print(real_url)
